package com.snail.poker.web.action;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.json.annotations.JSON;

import com.snail.poker.model.Equipment;
import com.snail.poker.service.EquipmentService;
import com.snail.poker.uitls.Constant;
import com.snail.poker.web.bean.PageBean;

/**
 * 移动设备的Action
 * 
 * @author Snail
 * 
 */
public class EquipmentAction extends BaseAction {
	private static final Log log = LogFactory.getLog(EquipmentAction.class);

	private EquipmentService equipmentManage;
	private Equipment equipment;
	private PageBean pageBean;

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public Equipment getEquipment() {
		return equipment;
	}

	public void setEquipment(Equipment equipment) {
		this.equipment = equipment;
	}

	@JSON(serialize = false)
	public EquipmentService getEquipmentManage() {
		return equipmentManage;
	}

	public void setEquipmentManage(EquipmentService equipmentManage) {
		this.equipmentManage = equipmentManage;
	}

	/**
	 * 移动设备登录平台的日志记录
	 * 
	 * @return
	 */
	public String login() {
		if (null == equipment) {
			super.putMessage("未发现可操作的数据.");
			return ERROR;
		}
		try {
			this.equipment.setCreateIp(super.getIpAddress());
			Equipment equip = this.equipmentManage.saveEquipment(equipment);
			super.session.put(Constant.EQUIPMENT_SESSION_KEY, equip);
			super.message = super.request.getSession().getId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
			super.putMessage(e.getMessage());
		}
		return SUCCESS;
	}

	@Override
	public String query() {
		// TODO Auto-generated method stub
		this.pageBean = this.equipmentManage.queryEquipment();
		return super.query();
	}

	/**
	 * 状态变更
	 * 
	 * @return
	 */
	public String change() {
		if (null == this.equipment) {
			super.putMessage("未发现可操作数据.");
			return ERROR;
		}
		if (this.equipment.getStatus() < 1 || this.equipment.getStatus() > 3) {
			super.putMessage("未定义该状态.");
			return ERROR;
		}
		try {
			Equipment equip = (Equipment) super.session
					.get(Constant.EQUIPMENT_SESSION_KEY);
			boolean flag = this.equipmentManage.changeStatus(equip,
					this.equipment.getStatus());
			if (flag) {
				super.session.clear();
				super.session = null;
			}
			super.message = "状态已变";
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e);
			super.putMessage(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
}
